// gulp的入口文件

// gulp定义任务
// 通过 yarn gulp foo 执行
exports.foo = done => {
    console.log('foo task working')
    done() // 标识任务完成
}

// 通过 yarn gulp 执行
exports.default = done => {
    console.log('default task work')
    done()
}

/* gulp4.0以前的任务定义方式 已经不推荐了 */
const gulp = require('gulp')
gulp.task('bar', done => {
    console.log('bar work')
    done()
})


// gulp定义组合任务(串行任务 和 并行任务)
const { series, parallel } = require('gulp')

const task1 = done => {
    setTimeout(() => {
        console.log('task1 working')
        done()
    }, 1000)
}

const task2 = done => {
    setTimeout(() => {
        console.log('task2 working')
        done()
    }, 1000)
}

const task3 = done => {
    setTimeout(() => {
        console.log('task3 working')
        done()
    }, 1000)
}

exports.foo1 = series(task1, task2, task3)
exports.foo2 = parallel(task1, task2, task3)


// gulp异步任务的三种方式
// 方式一 通过回调函数done
exports.callback = done => {
    console.log('callback task')
    done() // 标识任务成功
}
exports.callback_error = done => {
    console.log('callback task 2')
    done(new Error('task failed!')) // 标识任务失败
}

// 方式二 通过Promise.resolve() / Promise.reject()
exports.promise = () => {
    console.log('promise task')
    return Promise.resolve() // 标识成功
}
exports.promise_error = () => {
    console.log('promise task2')
    return Promise.reject(new Errow('task failed!'))
}

// 方式三 通过async/await
const timeout = time => {
    return new Promise(resolve => {
        setTimeout(resolve, time)
    })
}
exports.async = async () => {
    await timeout(1000)
    console.log('async task')
}

// 方式四 通过return stream
const fs = require('fs')
exports.stream = () => {
    const readStream = fs.createReadStream('package.json')
    const writeStream = fs.createWriteStream('temp.txt')
    readStream.pipe(writeStream)
    return readStream
}
// 相当于
exports.stream2 = done => {
    const readStream = fs.createReadStream('package.json')
    const writeStream = fs.createWriteStream('temp.txt')
    readStream.pipe(writeStream)
    readStream.on('end', () => {
        done()
    })
}
